import api from '../helpers/wxApi'
import { Server } from '../server'
import { BaseService } from './BaseService'

export class WxApiService extends BaseService {
  constructor(server: Server) {
    super(server)
  }

  public async getAccessToken() {
    const oldAccessToken = await this.checkAccessTokenValidate()
    if (oldAccessToken) {
      return oldAccessToken
    }
    const { errcode, accessToken, expiresIn } = await api.getAccessToken()
    if (errcode === 0) {
      await this.server.redisService.setAccessToken({ accessToken, expireAt: expiresIn + Date.now() })
      return accessToken
    } else {
      return null
    }
  }

  private async checkAccessTokenValidate(): Promise<string> {
    const redisService = this.server.redisService
    const now = new Date().getTime()
    const { accessToken, expireAt } = await redisService.getAccessToken()
    if (!accessToken || !expireAt) {
      return ''
    }

    // 接近当前时间 1000s 的范围也当做失效
    if (expireAt < now - 1000) {
      return ''
    }

    return accessToken
  }
}
